﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Reflection;

namespace Niaofei.Injcetion;

public static class InjectionExtension
{
    /// <summary>
    /// 添加服务
    /// </summary>
    public static void InjectionService(this IServiceCollection services, Assembly[] assemblies)
    {
        foreach (var assembly in assemblies)
        {
            var types = assembly.GetTypes();

            foreach (var type in types)
            {
                services.AddServices(type);
            }
        }
    }

    private static void AddServices(this IServiceCollection services, Type type)
    {
        try
        {
            var injectionAttribute = type.GetCustomAttribute<InjectionAttribute>();

            if (injectionAttribute == null)
            {
                return;
            }

            if (injectionAttribute.Type == null)
            {
                switch (injectionAttribute.ServiceLifetime)
                {
                    case ServiceLifetime.Singleton:
                        services.AddSingleton(type);
                        Console.WriteLine($"单例服务注入：抽象层：{type.FullName},实现层：{type.FullName}。");
                        return;
                    case ServiceLifetime.Scoped:
                        services.AddScoped(type);
                        Console.WriteLine($"作用域服务注入：抽象层：{type.FullName},实现层：{type.FullName}。");
                        return;
                    case ServiceLifetime.Transient:
                        Console.WriteLine($"瞬态服务注入：抽象层：{type.FullName},实现层：{type.FullName}。");
                        services.AddTransient(type);
                        return;
                }
            }
            else
            {
                switch (injectionAttribute.ServiceLifetime)
                {
                    case ServiceLifetime.Singleton:
                        services.AddSingleton(injectionAttribute.Type, type);
                        Console.WriteLine($"单例服务注入：抽象层：{injectionAttribute.Type.FullName},实现层：{type.FullName}。");
                        return;
                    case ServiceLifetime.Scoped:
                        services.AddScoped(injectionAttribute.Type, type);
                        Console.WriteLine($"作用域服务注入：抽象层：{injectionAttribute.Type.FullName},实现层：{type.FullName}。");
                        return;
                    case ServiceLifetime.Transient:
                        services.AddTransient(injectionAttribute.Type, type);
                        Console.WriteLine($"瞬态服务注入：抽象层：{injectionAttribute.Type.FullName},实现层：{type.FullName}。");
                        return;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}
